<?php


namespace app\db\admin;

use app\table\CmsTable;

/**
 * 角色关系表 数据库操作层
 */
class D_adminRoleFunc
{

    /** 直接使用sql时使用,带表前缀
     * @return string
     */
    private function getTableName(): string
    {
        return CmsTable::member_admin_role_func();
    }

    /**
     * 获取数据
     * @param $paramObj
     * @return array
     */
    public function getData($paramObj = "")
    {
        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            try {
                $ret = Db()->name(CmsTable::member_admin_role_func())->field("*")->select();
                $final_arr["result"]=$ret;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**取功能被那些角色id绑定信息
     * @param $paramObj
     * @return array
     */
    public function getFuncBindRole($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'funcId' => 'require|number'
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "funcId", "=", $dataObj->request->funcId
            );

            try {
                $ret = Db()->name(CmsTable::member_admin_role_func())->field("roleId")->where($where)->select();
                foreach ($ret as $k => $v) {
                    $final_arr["result"][] = $v["roleId"]; //只要id
                }
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**取角色绑定功能ids信息
     * @param $paramObj
     * @return array
     */
    public function getRoleBindFunc($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'roleId' => 'require|number'
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "roleId", "=", $dataObj->request->roleId
            );

            try {
                $ret = Db()->name(CmsTable::member_admin_role_func())->field("funcId")->where($where)->select();
                foreach ($ret as $k => $v) {
                    $final_arr["result"][] = $v["funcId"]; //只要id
                }
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**删除角色绑定功能
     * @param $paramObj
     * @return array
     */
    public function delete($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'roleId' => 'require|number',
                'funcIds' => 'require|array|array_isInt',
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();


            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where = array();
            $where[] = ["roleId", "=", $dataObj->request->rodeId];
            $where[] = ["funcId", "IN", $dataObj->request->funcIds];

            try {
                $result = Db()->name(CmsTable::member_admin_role())->delete();
                $final_arr["result"] = $result; //返回信息放入结果
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**添加角色绑定功能  //有联合索引 需要逻辑层排除重复项
     * @param $paramObj
     * @return array
     */
    public function addBatch($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求 校验后的数据,包括默认值都会放这里
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'roleId' => 'require|number',
                'funcIds' => 'require|array|array_isInt',
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        if ($final_arr["error_no"] == 0) {
            $where[] = array(
                "roleId", "=", $dataObj->request->id
            );
            $data = array();
            foreach ($dataObj as $key => $value) {
                $data[] = array(
                    "roleId" => $dataObj->request->roleId,
                    "funcId" => $value,
                );
            }


            try {
                $result = Db()->name(CmsTable::member_admin_role_func())->where($where)->insertBatch($data);
                $final_arr["result"] = $result; //返回信息放入结果
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**更新角色权限信息,事务 删无加有
     * @param $paramObj
     * @return array
     */
    public function setRoleBindFunc($paramObj = ""): array
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();  //请求 校验后的数据,包括默认值都会放这里
        $dataObj->data = paramsObj();        //data  数据
        $dataObj->data->use_trans = false;    // 是否使用use_trans
        $dataObj->result = array();           //结果

        $final_arr = logInit();               //日志初始化
        //校验数据合法
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0); //获取是否混合数据 1混合 0 只用默认
            $params = parseToArr($paramObj, "params", array());//  参数

            $rules = getKeyDefaultRule(array(           //设置规则 如果为空就用默认规则
                'roleId' => 'require|number',
                'id' => 'must',
            ));
            $messages = getValidateMessage($rules); //验证规则提示  继承客户端的消息信息
            $dataDefault = array();

            $paramsObj = paramsObj();  //新建一个空对象
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;

            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }

        //执行数据操作
        $oleFunc = [];
        //获取已有绑定功能
        if ($final_arr["error_no"] == 0) {

            $where[] = array(
                "roleId", "=", $dataObj->request->roleId
            );
            try {
                $ret = Db()->name(CmsTable::member_admin_role_func())->field("funcId")->where($where)->select();
                foreach ($ret as $k => $v) {
                    $oleFunc[] = $v["funcId"]; //只要id
                }
            } catch (\Throwable $e) {
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }

        if ($final_arr["error_no"] == 0) {
           if ($dataObj->request->id==""||$dataObj->request->id==null){
               $newFunc=array();
           }else{
               $newFunc = is_array($dataObj->request->id) ? $dataObj->request->id : explode(",", $dataObj->request->id);
           }

            //===获取需要删除的func 和增加的func
            $deleteFunc = array_diff($oleFunc, $newFunc);
            $addFunc = array_diff($newFunc, $oleFunc);
            if (count($deleteFunc) == 0 && count($addFunc) == 0) {
                $final_arr["result"]["delete"] = 0; //返回信息放入结果
                $final_arr["result"]["add"] = 0; //返回信息放入结果
                return $final_arr;      //没有数据要更新直接返回成功吧
            }
        }




        if ($final_arr["error_no"] == 0) {

            Db()->startTrans();
            try {

                if (count($deleteFunc) > 0) {
                    $where = [["roleId", "=", $dataObj->request->roleId], ["funcId", "IN", $deleteFunc]];
                    $result = Db()->name(CmsTable::member_admin_role_func())->where($where)->delete();
                    $final_arr["result"]["delete"] = $result["affected_rows"]; //返回信息放入结果
                } else {
                    $final_arr["result"]["delete"] = 0;
                }

                if (count($addFunc) > 0) {
                    $data = [];
                    foreach ($addFunc as $key => $value) {
                        $data[] = array("roleId" => $dataObj->request->roleId, "funcId" => $value);
                    }
                    $result = Db()->name(CmsTable::member_admin_role_func())->insertBatch($data);
                    $final_arr["result"]["add"] = $result["affected_rows"]; //返回信息放入结果
                } else {
                    $final_arr["result"]["add"] = 0;
                }

                Db()->commitTrans(); //提交事务
            } catch (\Throwable $e) {
                Db()->rollbackTrans();//回滚
                //记录日志信息
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }

        }
        return $final_arr;
    }


}